﻿using System;
using System.IO;
using System.Windows.Forms;

using ProfileManager.DataAccess;
using ProfileManager.Forms;
using ProfileManager.Helpers;
using ProfileManager.Properties;

namespace ProfileManager
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length != 0)
            {
                string cmd = args[0].Trim(new[] { '/', '-' });
                if (!string.IsNullOrEmpty(cmd))
                {
                    if (cmd.Equals("newbase", StringComparison.OrdinalIgnoreCase))
                    {
                        if (
                            MessageBox.Show(Resources.NewDbWillBeCreate, Resources.CreatingDb,
                                            MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation,
                                            MessageBoxDefaultButton.Button1) == DialogResult.OK)
                        {
                            StartWithCreatingDb();
                        }
                    }
                    else if (cmd.Equals("encrypt", StringComparison.OrdinalIgnoreCase))
                    {
                        if (args[1].Trim().Equals("-f"))
                        {
                            string filePath = string.Format(@"{0}", args[2].Trim());
                            if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
                            {
                                FileSystem.EncryptFile(filePath);
                            }
                        }
                        else if (args[1].Trim().Equals("-s"))
                        {
                            FileSystem.EncryptString(args[2].Trim());
                        }
                    }
                }
            }
            else
            {
                StartProgram();
            }
        }

        private static void StartWithCreatingDb()
        {
            string dbPath = Path.Combine(Application.StartupPath, "db");
            if (FileSystem.CreateDirectory(dbPath))
            {
                if (CommonDb.CreateFullDatabase(dbPath))
                {
                    StartProgram();
                }
                else
                {
                    Application.Exit();
                }
            }
            else
            {
                Application.Exit();
            }
        }

        private static void StartProgram()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new LoginForm());
        }
    }
}
